package com.imut.lagain.controller;

import com.imut.lagain.service.IFinalPasswordService;
import com.imut.lagain.util.JwtUtil;
import com.imut.lagain.util.ValidationUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.*;
import jakarta.validation.Valid;

import java.util.HashMap;
import java.util.Map;

/**
 * 最终答案之锁控制器
 */

@RestController
@RequestMapping("/api/final")
@RequiredArgsConstructor
@Validated
public class FinalAnswerController {
    private static final Logger log = LoggerFactory.getLogger(FinalAnswerController.class);
    
    private final IFinalPasswordService finalPasswordService;
    private final JwtUtil jwtUtil;
    
    /**
     * 验证最终密码
     * @param authorization JWT令牌
     * @param request 密码验证请求
     * @return 验证结果
     */
    @PostMapping("/verify")
    public ResponseEntity<Map<String, Object>> verifyPassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody PasswordVerifyRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            String inputPassword = request.getPassword();
            if (inputPassword == null || inputPassword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (finalPasswordService.validateCurrentPassword(inputPassword.trim())) {
                Map<String, Object> finalContent = getFinalContent();
                
                response.put("success", true);
                response.put("message", "密码验证成功");
                response.put("content", finalContent);
                
                log.info("Final password verified successfully by user: {}", jwtUtil.getUserIdFromToken(token));
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "密码错误，请重试");
                
                log.warn("Failed password attempt by user: {}", jwtUtil.getUserIdFromToken(token));
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to verify final password", e);
            response.put("success", false);
            response.put("message", "密码验证失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取最终内容
     * @return 最终内容
     */
    private Map<String, Object> getFinalContent() {
        Map<String, Object> content = new HashMap<>();
        content.put("type", "text");
        content.put("title", "最终的话");
        content.put("message", "亲爱的，如果你看到这里，说明我们一起走过了这段美好的记忆之旅。\n\n" +
                              "无论我们的关系走向何方，这些共同的回忆都是珍贵的。\n\n" +
                              "感谢你愿意和我一起创造这些美好的时光。\n\n" +
                              "愿我们都能在各自的人生道路上找到属于自己的幸福。");
        
        return content;
    }
    
    /**
     * 管理员更新密码（可选功能）
     * @param request 更新密码请求
     * @return 更新结果
     */
    @PostMapping("/admin/password")
    public ResponseEntity<Map<String, Object>> updatePassword(
            @Valid @RequestBody UpdatePasswordRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String newPassword = request.getNewPassword();
            if (newPassword == null || newPassword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "新密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            response.put("success", true);
            response.put("message", "密码更新成功，请重启应用使配置生效");
            
            log.info("Final password updated by admin");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to update final password", e);
            response.put("success", false);
            response.put("message", "密码更新失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 密码验证请求DTO
     */
    public static class PasswordVerifyRequest {
        @NotBlank(message = "密码不能为空")
        @Size(min = 1, max = 100, message = "密码长度必须在1-100字符之间")
        private String password;
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
    }
    
    /**
     * 更新密码请求DTO
     */
    public static class UpdatePasswordRequest {
        @NotBlank(message = "管理员密钥不能为空")
        @Size(min = 1, max = 100, message = "管理员密钥长度必须在1-100字符之间")
        private String adminKey;
        
        @NotBlank(message = "新密码不能为空")
        @Size(min = 1, max = 100, message = "新密码长度必须在1-100字符之间")
        private String newPassword;
        
        public String getAdminKey() {
            return adminKey;
        }
        
        public void setAdminKey(String adminKey) {
            this.adminKey = adminKey;
        }
        
        public String getNewPassword() {
            return newPassword;
        }
        
        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
}

